package com.frxuexi.mysign

import android.util.Log
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.map.MyLocationData
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.entity.SignBeanItem
import com.frxuexi.lib_base.http.Const
import com.frxuexi.lib_base.mvi.BaseActivity
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.mysign.databinding.ActivityMySignBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.util.Timer
import kotlin.concurrent.timerTask


@Route(path = "/mysign/MySignActivity")
@AndroidEntryPoint
class MySignActivity : BaseActivity<ActivityMySignBinding,MySignIntent,MySignViewModel>() {
    override val binding: ActivityMySignBinding by lazy { ActivityMySignBinding.inflate(layoutInflater) }
    override val vm: MySignViewModel by viewModels<MySignViewModel>()
    var timer:Timer?=null
    lateinit var mLocationClient:LocationClient

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        ToastUtils.showLong("打卡成功")
                    }
                    is UiState.onError->{
                        Log.i("lr",it.msg)
                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {
        lifecycleScope.launch(Dispatchers.IO) {
            timer= Timer()
            timer?.schedule(timerTask {
                lifecycleScope.launch (Dispatchers.Main){
                    binding.signTime.setText(vm.getTime(System.currentTimeMillis()))
                }
            },0,1000)
        }
        val millis = System.currentTimeMillis()
        val week = TimeUtils.getChineseWeek(millis).replace("周", "星期")
        binding.signDate.setText("${vm.getDataFont(millis)} ${week}")


        binding.signAdd.setOnClickListener {
            ARouter.getInstance().build("/mysign/MySignListActivity").navigation()
        }

        initMap()
        val myNum = SPUtils.getInstance().getInt("num", 0)
        if(myNum==1){
            binding.signTvdaka.setText("下午打卡")
            binding.signTvtime.setText("14:00-18:00")
        }else if(myNum==2){
            binding.btnSign.isEnabled=false
        }

        binding.btnSign.setOnClickListener {
            var status="正常"
            val time = vm.getDataTime(System.currentTimeMillis())
            if(myNum==0){//上午打卡
                SPUtils.getInstance().put("num",1)
                binding.signTvdaka.setText("下午打卡")
                binding.signTvtime.setText("14:00-18:00")
                if(time.split(" ")[1]>"09:00:00"){
                    status="迟到"
                }
            }else if(myNum==1){//下午打卡
                SPUtils.getInstance().put("num",2)
                binding.btnSign.isEnabled=false
                if(time.split(" ")[1]<"18:00:00"){
                    status="早退"
                }
            }
            val item = SignBeanItem(
                time,
                SPUtils.getInstance().getString("lat"),
                null,
                "天津市",
                time,
                status,
                SPUtils.getInstance().getInt(Const.UID)
            )
            vm.sendIntent(MySignIntent.sign(item))

        }
    }

    private fun initMap() {
        LocationClient.setAgreePrivacy(true)
        //定位初始化
       mLocationClient = LocationClient(this)

//通过LocationClientOption设置LocationClient相关参数

//通过LocationClientOption设置LocationClient相关参数
        val option = LocationClientOption()
        option.isOpenGps = true // 打开gps

        option.setCoorType("bd09ll") // 设置坐标类型

        option.setScanSpan(1000)

//设置locationClientOption

//设置locationClientOption
        mLocationClient.setLocOption(option)

//注册LocationListener监听器

//注册LocationListener监听器
        val myLocationListener: MyLocationListener = MyLocationListener()
        mLocationClient.registerLocationListener(myLocationListener)
//开启地图定位图层
//开启地图定位图层
        mLocationClient.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        if(timer!=null){
            timer?.cancel()
            timer=null
        }
        mLocationClient.stop();
    }


    inner class MyLocationListener : BDAbstractLocationListener() {
        override fun onReceiveLocation(location: BDLocation) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null) {
                return
            }
            Log.i("===","${location.latitude},${location.longitude}")
            if(SPUtils.getInstance().getString("lat","").isNotEmpty()){
                mLocationClient.stop();
            }else {
                SPUtils.getInstance().put("lat", "${location.latitude},${location.longitude}")
            }

//            Log.i("====","${location.city}")
        }
    }


}